const express = require("express");
const cors = require("cors");
const app = express();

const jwt = require("jsonwebtoken"); // 生成token
const expressJWT = require("express-jwt"); // 解析token

app.use(cors());
app.use(express.json());
app.use(express.urlencoded());

const secretKey = "yjwBest";

app.use(
  expressJWT({ secret: secretKey, algorithms: ["HS256"] }).unless({
    path: ["/", "/login"],
  })
);

app.post("/login", (req, res) => {
  if (req.body.uname != "admin" || req.body.pwd != "123456") {
    return res.send({ msg: "用户名或密码错误" });
  }

  let token = jwt.sign({ uname: req.body.uname }, secretKey, {
    expiresIn: "30s",
  });
  res.send({
    status: 200,
    msg: "登录成功",
    token: token,
  });
});

app.get("/api/user", (req, res) => {
  console.log(req.user);
  res.send({ name: "user information", user: req.user });
});

app.get("/logout", (req, res) => {
    res.send({
        msg:'退出成功',
        status:200
    })
});

app.use((err, req, res, next) => {
  console.log(err);
  if (err.name == "UnauthorizedError") {
    return res.send({
      msg: "token 无效获取 请重新登录",
      status: 401,
    });
  }
  res.send({
    status: 500,
    // msg:'服务端错误'
    msg: "未知错误",
  });
  next();
});

app.listen(3000,()=>{
    console.log('3000 running')
})